package JmmAndMultiThread.MultiThreads;

import java.util.concurrent.CountDownLatch;

public class MultiThreadCountDownLatch {
    public static void main(String[] args) {
        //简单点来说，CountDownLatch 就是一个倒计数器，我们把初始计数值设置为3，当 D 运行时，
        // 先调用 countDownLatch.await() 检查计数器值是否为 0，若不为 0 则保持等待状态；
        // 当A B C 各自运行完后都会利用countDownLatch.countDown()，将倒计数器减 1，当三个都运行完后，计数器被减至 0；
        // 此时立即触发 D 的 await() 运行结束，继续向下执行。
        //因此，CountDownLatch 适用于一个线程去等待多个线程的情况。
        //控制某个线程最后运行
        // CountDownLatch countDownLatch=new CountDownLatch(N);
        //当n减到0时awai()才会结束
        CountDownLatch countDownLatch=new CountDownLatch(4);
        new Thread(()->{
            System.out.println(Thread.currentThread().getName()+" waiting……");
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" finished");
        },"A").start();
        new Thread(()->{
            System.out.println(Thread.currentThread().getName()+" finished");
            countDownLatch.countDown();
        },"B").start();
        new Thread(()->{
            System.out.println(Thread.currentThread().getName()+" finished");
            countDownLatch.countDown();
        },"C").start();
        new Thread(()->{
            System.out.println(Thread.currentThread().getName()+" finished");
            countDownLatch.countDown();
        },"D").start();
        new Thread(()->{
            System.out.println(Thread.currentThread().getName()+" finished");
            countDownLatch.countDown();
        },"E").start();
    }
}
